type EventHandler<T = any> = (payload: T) => void;

class EBus {
    private events: Record<string, Set<EventHandler>> = {};
    
    on<T = any>(eventName: string, handler: EventHandler<T>) {
        if (typeof handler !== 'function') {
            throw new Error('Handler must be a function');
        }
        (this.events[eventName] ??= new Set()).add(handler);
    }

    emit<T = any>(eventName: string, payload?: T) {
        const handlers = this.events[eventName];
        if (!handlers) return;
        
        handlers.forEach(handler => {
            try {
                handler(payload);
            } catch (err) {
                console.error(`Error in event handler for ${eventName}:`, err);
            }
        });
    }

    off(eventName: string, handler?: EventHandler) {
        if (!handler) {
            // 移除该事件所有监听器
            delete this.events[eventName];
            return;
        }
        this.events[eventName]?.delete(handler);
    }

    once<T = any>(eventName: string, handler: EventHandler<T>) {
        const onceHandler = (payload: T) => {
            handler(payload);
            this.off(eventName, onceHandler);
        };
        this.on(eventName, onceHandler);
    }

    // 清理所有事件监听器
    clear() {
        this.events = {};
    }
}

export const bus = new EBus();